"""
@author: forward
@contact: 1@qq.com
@software: garner
@file: code.py
@time: 2021/11/25 17:09
"""

from typing import List
from sqlalchemy import BinaryExpression, select
from forward.api.admin.schemas.lucky.code import CodeDetailOutSchema
from forward.dependencies.database import db
from forward.model.orm.base import BaseORM
from forward.model.schemas.lucky.code import (
    CodeCreateSchema,
    CodeOutSchema,
    CodeUpdateSchema,
)
from forward.model.tables.activity import ActivityModel, CodeModel, PrizeModel
from forward.model.tables.merchant import MerchantModel
from forward.utils.page_utils import PageSchema, PageUtils


class CodeORM(BaseORM[CodeOutSchema,]):
    """code orm

    Args:
        BaseORM (_type_): _description_
    """

    MODEL = CodeModel
    OUT_SCHEMA = CodeOutSchema

    async def list(
        self,
        where: List[BinaryExpression] | None = None,
        page_num: int = 1,
        page_size: int = 15,
        **kwargs
    ) -> PageSchema[CodeDetailOutSchema]:
        """
        code 分页
        """
        where_conditions = []
        if where is not None:
            where_conditions.extend(where)
        statement = (
            select(
                CodeModel,
                PrizeModel.name.label("prize_name"),
                MerchantModel.name.label("merchant_name"),
                ActivityModel.title.label("activity_title"),
            )
            .where(*where_conditions)
            .outerjoin(PrizeModel, CodeModel.prize_id == PrizeModel.id)
            .outerjoin(ActivityModel, CodeModel.activity_id == ActivityModel.id)
            .outerjoin(MerchantModel, ActivityModel.merchant_id == MerchantModel.id)
            .order_by(CodeModel.id.desc())
        )
        pagination = await PageUtils.paginate(
            db=db,
            query=statement,
            page_num=page_num,
            page_size=page_size,
            schema=CodeDetailOutSchema,
            **kwargs
        )
        return pagination
